<?php

namespace App\Http\Controllers\Frontend;

use App\Http\Controllers\Controller;
use App\Library\Helper;
use App\Model\Device;
use App\Model\DeviceThree;
use App\Model\DeviceTwo;
use App\Model\Group;
use App\Model\InverterData;
use App\Model\InverterDataThree;
use App\Model\InverterDataTwo;
use App\Model\Site;
use App\Model\StatisticsDeviceDayEnergy;
use Illuminate\Http\Request;

class DeviceController extends Controller
{

    public function getDevices(Request $request)
    {
        $user = $this->_getCurrentUser();
        $user_id = $user->id;
        switch ($user_id){
            case $user_id < 17:
                $devices = Device::getDevicesByUserId($user->id);
                break;
            case $user_id >=17 && $user_id < 43;
                $devices = DeviceTwo::getDevicesByUserId($user->id);
                break;
            default:
                    $devices = DeviceThree::getDevicesByUserId($user->id);
        }
//        if($user->id <17) {
//            $devices = Device::getDevicesByUserId($user->id);
//        }else{
//            $devices = DeviceTwo::getDevicesByUserId($user->id);
//        }
        foreach ($devices as $device) {
//            if($user->id <17) {
//                $ivd = InverterData::getLastInverterDataByDeviceId($user->id, $device->device_id);
//            }else{
//                $ivd = InverterDataTwo::getLastInverterDataByDeviceId($user->id, $device->device_id);
//            }
            switch ($user_id){
                case $user_id < 17:
                    $ivd = InverterData::getLastInverterDataByDeviceId($user->id, $device->device_id);
                    break;
                case $user_id >=17 && $user_id < 43;
                    $ivd = InverterDataTwo::getLastInverterDataByDeviceId($user->id, $device->device_id);
                    break;
                default:
                    $ivd = InverterDataThree::getLastInverterDataByDeviceId($user->id, $device->device_id);
            }
            //status 1，2，3 正常，警报，离线

            //数据不存在则离线、功率为0
            if (!$ivd) {
                $device->status = 3;
                $device->power = 0;
            } else {
                //最近一次数据为20分钟前则离线功率为0
                $now = time();
                $created_at = strtotime($ivd->created_at);
                if ($now - $created_at > 60 * 60) {
                    $device->status = 3;
                    $device->power = 0;
                } else {
                    $device->power = $ivd->ActivePower;
                    //最近一条数据为警报，则显示警报状态
                    //状态码小于等于3都是正常运行，具体请参考Helper::transError()
                    if ($ivd->IVStatus <= 3) {
                        $device->status = 1;
                    } else {
                        $device->status = 2;
                    }
                }
            }
            //修改状态为中文
            if ($device->status == 1) {
                $device->status = '运行中';
            }
            if ($device->status == 2) {
                $device->status = '报警';
            }
            if ($device->status == 3) {
                $device->status = '离线';
            }
        }

        return $this->json_success($devices);
    }

    public function getDetail(Request $request)
    {
        $user=$this->_getCurrentUser();
        $id = $request->input('id');
        $user_id = $user->id;
        switch ($user_id){
            case $user_id < 17:
                $devices = Device::find($id);
                break;
            case $user_id >=17 && $user_id < 43;
                $devices = DeviceTwo::find($id);
                break;
            default:
                $devices = DeviceThree::find($id);
        }
//        if($user->id<17) {
//            $device = Device::find($id);
//        }else{
//            $device = DeviceTwo::find($id);
//        }
        $today_date = date('Y-m-d', time());

        $begin_date = date('Y-m-d', strtotime('-30 day'));
        $end_date = date('Y-m-d');

        return view('frontend.device.detail', [
            'device' => $devices,
            'today_date' => $today_date,
            'begin_date' => $begin_date,
            'end_date' => $end_date
        ]);
    }

    public function getWorking()
    {
        $redis = $this->_Redis();
        $user=$this->_getCurrentUser();
        $site=Site::where('user_id',$user->id)->first();
        $user_id = $user->id;
//        foreach($sites as $site)
//        {
//            $groups=$site->groups()->get();
        $groups = Group::where('site_id',$site->id)->get();
            $obj=[];
            foreach($groups as $group)
            {
//                if($user->id<17) {
//                    $devices = Device::getDevicesByGroupId($group->id);
//                }else{
//                    $devices = DeviceTwo::getDevicesByGroupId($group->id);
//                }
                switch ($user_id){
                    case $user_id < 17:
//                        $devices = Device::getDevicesByUserId($user->id);
                           $devices = Device::getDevicesByGroupId($group->id);
                        break;
                    case $user_id >=17 && $user_id < 43;
//                        $devices = DeviceTwo::getDevicesByUserId($user->id);
                             $devices = DeviceTwo::getDevicesByGroupId($group->id);
                        break;
                    default:
//                        $devices = DeviceThree::getDevicesByUserId($user->id);
                            $devices = DeviceThree::getDevicesByGroupId($group->id);
                }

                $res=[];
                foreach($devices as &$device)
                {
//                    if($user->id<17) {
//                        $device->working = Device::getWorkingDevicesByDeviceId($device->device_id, $user->id);
//                    }else{
//                        $device->working = DeviceTwo::getWorkingDevicesByDeviceId($device->device_id, $user->id);
//                    }
                    $key = "xy:industry:data:".$device->site_id.":".$device->device_id;
                    $s = $redis->get($key);

                    switch ($user_id){
                        case $user_id<17:
                            $device->working = Device::getWorkingDevicesByDeviceId($s, $user_id);
                            break;
                        case $user_id >= 17 && $user_id < 43:
                            $device->working = DeviceTwo::getWorkingDevicesByDeviceId($s, $user_id);
                            break;
                        default:
                            $device->working = DeviceThree::getWorkingDevicesByDeviceId($s, $user_id);
                    }

                }
                array_push($res,$devices->toArray());
                $obj[$group->name]=$res;
            }
            $finalResults[$site->name]=$obj;
//        }
        return view('frontend.device.work-condition',['finalResults'=>$finalResults]);

    }






    public function  getStatus(Request $request)
    {
        $user = $this->_getCurrentUser();
        $user_id = $user->id;
        $site=Site::where('user_id',$user->id)->first();
        $device_id=$request->input('device_id');
        switch ($user_id){
            case $user_id < 17:
                $res['GenCap'] = InverterData::getTodayGenCapByDeviceId($user_id, $device_id);
                $res['temp'] = InverterData::getTodayTemp($user_id, $device_id);
                break;
            case $user_id >= 17 && $user_id < 43:
                $res['GenCap'] = InverterDataTwo::getTodayGenCapByDeviceId($user->id, $device_id);
                $res['temp'] = InverterDataTwo::getTodayTemp($user->id, $device_id);
            default:
                $res['GenCap'] = InverterDataThree::getTodayGenCapByDeviceId($user->id, $device_id);
                $res['temp'] = InverterDataThree::getTodayTemp($user->id, $device_id);
        }

//        if($user->id<17) {
//            $res['GenCap'] = InverterData::getTodayGenCapByDeviceId($user->id, $device_id);
//            $res['temp'] = InverterData::getTodayTemp($user->id, $device_id);
//        }else{
//            $res['GenCap'] = InverterDataTwo::getTodayGenCapByDeviceId($user->id, $device_id);
//            $res['temp'] = InverterDataTwo::getTodayTemp($user->id, $device_id);
//        }
        return $this->json_success($res);
    }

    public function postEnergyData(Request $request)
    {
        $user=$this->_getCurrentUser();
        $user_id = $user->id;
        $device_id = $request->input('device_id');
        if($user->id <17) {
            $device_id = $this->__getDeviceId($device_id);
        }else{
            $device_id = $this->__getDeviceTwoId($device_id);
        }
        $type = $request->input('type');
        $time_type = $request->input('time_type');
        $start = $request->input('start');
        $end = $request->input('end');

        $start_date = strtotime($start);
        $end_date = strtotime($end);

        $result = [];
        //电脑数据
        if ($type == 'energy') {
            $labels = [];
            $datas = [];
            if ($time_type == 'm') {
//                $s_y = (int)date('Y', $start_date);
//                $s_m = (int)date('m', $start_date);
//                $e_y = (int)date('Y', $end_date);
//                $e_m = (int)date('m', $end_date);
//                $interval_month = 12 * ($e_y - $s_y) + ($e_m - $s_m);
//
//
//                for ($i = 0; $i <= $interval_month; $i++) {
//                    $m = date('Y-m', strtotime('+' . $i . ' month', $start_date));
//                    array_push($labels, $m);
//                    $energy = InverterData::getOneMonthGenCapByDeviceId($device_id, $m);
//                    array_push($datas, $energy);
//                }

                $s_y = (int)date('Y', $start_date);
                $s_m = (int)date('m', $start_date);
                $e_y = (int)date('Y', $end_date);
                $e_m = (int)date('m', $end_date);
                $interval_month = 12 * ($e_y - $s_y) + ($e_m - $s_m);


                for ($i = 0; $i <= $interval_month; $i++) {
                    $m = date('Y-m', strtotime('+' . $i . ' month', $start_date));
                    array_push($labels, $m);
                    $energy = StatisticsDeviceDayEnergy::getOneMonthByDeviceId($user->id,$device_id, $m);
                    array_push($datas, $energy);
                }

            }

            if ($time_type == 'd') {

                $sddes = StatisticsDeviceDayEnergy::getSomeByDeviceId($user->id,$device_id, $start, $end);
                $labels = [];
                $datas = [];
                foreach ($sddes as $sdde) {
                    array_push($labels, $sdde->date);
                    array_push($datas, $sdde->value);
                }

            }
            $result['labels'] = $labels;
            $result['data'] = $datas;
            return $this->json_success($result);
        }
        //功率数据
        if ($type == 'power') {
//            if($user->id<17) {
//                $ivds = InverterData::getSomeInverterDataByDeviceId($user->id, $device_id, $start, $end);
//            }else{
//                $ivds = InverterDataTwo::getSomeInverterDataByDeviceId($user->id, $device_id, $start, $end);
//            }
            switch ($user_id){
                case $user_id<17:
                    $ivds = InverterData::getSomeInverterDataByDeviceId($user_id, $device_id, $start, $end);
                    break;
                case $user_id >= 17 && $user_id < 43:
                    $ivds = InverterDataTwo::getSomeInverterDataByDeviceId($user_id, $device_id, $start, $end);
                    break;
                default:
                    $ivds = InverterDataThree::getSomeInverterDataByDeviceId($user_id, $device_id, $start, $end);
            }

            $labels = [];
            $datas = [];
            foreach ($ivds as $ivd) {
                array_push($labels, $ivd->created_at->format('Y-m-d H:i:s'));
                array_push($datas, $ivd->ActivePower);
            }
            $result['labels'] = $labels;
            $result['data'] = $datas;
            return $this->json_success($result);
        }

        return $this->json_error('不支持的类型！', 1002);


    }

    public function getLastInverterData(Request $request)
    {
        $user = $this->_getCurrentUser();
        $user_id = $user->id;
        $device_id = $request->input('device_id');
//        if($user->id <17) {
//            $device_id = $this->__getDeviceId($device_id);
//        }else{
//            $device_id = $this->__getDeviceTwoId($device_id);
//        }
        switch ($user_id){
            case $user_id<17:
                $device_id = $this->__getDeviceId($device_id);
                $inverter_data = InverterData::getLastInverterDataByDeviceId($user->id,$device_id);
                break;
            case $user_id >= 17 && $user_id < 43:
                $device_id = $this->__getDeviceTwoId($device_id);
                $inverter_data = InverterDataTwo::getLastInverterDataByDeviceId($user->id,$device_id);
                break;
            default:
                $device_id = $this->__getDeviceThreeId($device_id);
                $inverter_data = InverterDataThree::getLastInverterDataByDeviceId($user->id,$device_id);
        }
//        if($user->id<17){
//            $inverter_data = InverterData::getLastInverterDataByDeviceId($user->id,$device_id);
//        }else{
//            $inverter_data = InverterDataTwo::getLastInverterDataByDeviceId($user->id,$device_id);
//        }
        if ($inverter_data) {
            $inverter_data->status_label = Helper::transError($inverter_data->IVStatus, $inverter_data->IVType);
            return $this->json_success([$inverter_data]);
        } else {
            return $this->json_success([]);
        }

    }

    public function getSomeData(Request $request)
    {
        $user = $this->_getCurrentUser();
        $user_id = $user->id;
        $device_id = $request->input('device_id');
//        if ($user->id < 17){
//            $device_id = $this->__getDeviceId($device_id);
//        }else{
//            $device_id = $this->__getDeviceTwoId($device_id);
//        }
        $date = $request->input('date');
        $time = $request->input('time');

        if ($time == 'all') {
            $begin_time = $date . ' 6:00:00';
            $end_time = $date . ' 23:00:00';
        } else {
            $times = explode(',', $time);
            $time_b = $times[0];
            $time_e = $times[1];
            $begin_time = $date . ' ' . $time_b . ':00:00';
            $end_time = $date . ' ' . $time_e . ':00:00';
        }

//        if($user->id<17) {
//            $datas = InverterData::getSomeInverterDataByDeviceId($user_id, $device_id, $begin_time, $end_time);
//        }else{
//            $datas = InverterDataTwo::getSomeInverterDataByDeviceId($user_id, $device_id, $begin_time, $end_time);
//        }
        switch ($user_id){
            case $user_id<17:
                $device_id = $this->__getDeviceId($device_id);
                $datas = InverterData::getSomeInverterDataByDeviceId($user_id, $device_id, $begin_time, $end_time);
                break;
            case $user_id >= 17 && $user_id < 43:
                $device_id = $this->__getDeviceTwoId($device_id);
                $datas = InverterDataTwo::getSomeInverterDataByDeviceId($user_id, $device_id, $begin_time, $end_time);
                break;
            default:
                $device_id = $this->__getDeviceThreeId($device_id);
                $datas = InverterDataThree::getSomeInverterDataByDeviceId($user_id, $device_id, $begin_time, $end_time);
        }
        $results = [];
        $results['labels'] = [];
        $results['DCI1'] = [];
        $results['DCI2'] = [];
        $results['DCI3'] = [];
        $results['DCI4'] = [];
        $results['DCU1'] = [];
        $results['DCU2'] = [];
        $results['DCU3'] = [];
        $results['DCU4'] = [];
        $results['ACUA'] = [];
        $results['ACIA'] = [];
        $results['ACUB'] = [];
        $results['ACIB'] = [];
        $results['ACUC'] = [];
        $results['ACIC'] = [];
        $results['DayGenCap'] = [];
        foreach ($datas as $data) {
            $d = [];
            $d['y'] = $data->created_at->format('Y-m-d H:i:s');
            $d['DCI1'] = $data->DCI1;
            $d['DCI2'] = $data->DCI2;
            $d['DCI3'] = $data->DCI3;
            $d['DCI4'] = $data->DCI4;
            $d['DCU1'] = $data->DCU1;
            $d['DCU2'] = $data->DCU2;
            $d['DCU3'] = $data->DCU3;
            $d['DCU4'] = $data->DCU4;
            $d['ACUA'] = $data->ACUA;
            $d['ACIA'] = $data->ACIA;
            $d['ACUB'] = $data->ACUB;
            $d['ACIB'] = $data->ACIB;
            $d['ACUC'] = $data->ACUC;
            $d['ACIC'] = $data->ACIC;
            $d['DayGenCap'] = $data->DayGenCap;

            array_push($results['labels'], $data->created_at->format('Y-m-d H:i:s'));
            array_push($results['DCI1'], $data->DCI1);
            array_push($results['DCI2'], $data->DCI2);
            array_push($results['DCI3'], $data->DCI3);
            array_push($results['DCI4'], $data->DCI4);
            array_push($results['DCU1'], $data->DCU1);
            array_push($results['DCU2'], $data->DCU2);
            array_push($results['DCU3'], $data->DCU3);
            array_push($results['DCU4'], $data->DCU4);
            array_push($results['ACUA'], $data->ACUA);
            array_push($results['ACIA'], $data->ACIA);
            array_push($results['ACUB'], $data->ACUB);
            array_push($results['ACIB'], $data->ACIB);
            array_push($results['ACUC'], $data->ACUC);
            array_push($results['ACIC'], $data->ACIC);
            array_push($results['DayGenCap'], $data->DayGenCap);
        }
        return $this->json_success($results);

    }

    private function __getDeviceId($device_id)
    {
            $device = Device::find($device_id);
        if (!$device) {
            return $device_id;
        } else {
            return $device->device_id;
        }
    }

    private function __getDeviceTwoId($device_id)
    {
        $device = DeviceTwo::find($device_id);
        if (!$device) {
            return $device_id;
        } else {
            return $device->device_id;
        }
    }

    private function __getDeviceThreeId($device_id)
    {
        $device = DeviceThree::find($device_id);
        if (!$device) {
            return $device_id;
        } else {
            return $device->device_id;
        }
    }

}
